package com.coderzheaven.pack;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

import android.app.Activity;
import android.app.Dialog;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

/*DEV NOTE: PORT ISSUES with FIREWALL*/
public class DownloadFileDemo1 extends Activity {
	
    ProgressBar pb;
    Dialog dialog;
    int downloadedSize = 0;
    int totalSize = 0;
    
    long total = 0;
    TextView cur_val;
//    String dwnload_file_path = "http://coderzheaven.com/sample_folder/sample_file.png";
    
    String dwnload_file_path ="http://192.168.20.2/directory/1.txt	";
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
      
        Button b = (Button) findViewById(R.id.b1);
        b.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				
				doDownload("http://192.168.20.2/directory/ReviewerDAA.pdf", "ReviewerDAA.pdf");
				
				 showProgress("ReviewerDAA.pdf");
			        
//			        new Thread(new Runnable() {
//			            public void run() {
//			            	 downloadFile();
//			            }
//			          }).start();
			}
		});
    }
    
    protected void doDownload(final String urlLink, final String fileName) {
        Thread dx = new Thread() {

            public void run() {
                  File root = android.os.Environment.getExternalStorageDirectory();               
                  File dir = new File (root.getAbsolutePath() + "/Content2/"); 
                  if(dir.exists()==false) {
                          dir.mkdirs();
                     }
                  //Save the path as a string value

                try {
                        URL url = new URL(urlLink);
                        Log.i("FILE_NAME", "File name is " + fileName);
                        Log.i("FILE_URLLINK", "File URL is  " + url);
                        final URLConnection connection = url.openConnection();
                        connection.connect();
                        
                        // this will be useful so that you can show a typical 0-100% progress bar
                        final int fileLength = connection.getContentLength();
                        runOnUiThread(new Runnable() {
            			    public void run() {
            			    	pb.setMax(fileLength);
            			    }			    
            			});

                        // download the file
                        InputStream input = new BufferedInputStream(url.openStream());
                        OutputStream output = new FileOutputStream(dir+"/"+fileName);

                        byte bufferLength[] = new byte[1024];
                        int count;
                        
                        
                        while ((count = input.read(bufferLength)) != -1) {
                            total += count;
                            output.write(bufferLength, 0, count);
                            runOnUiThread(new Runnable() {
                			    public void run() {
                			    	pb.setProgress((int) total);
                			    	float per = (total / (float) fileLength) * 100;
                			    	cur_val.setText("Downloaded " + total + "KB / " + connection.getContentLength() + "KB (" + per + "%)" );
                			    }
                			});
                            
                        }

                        output.flush();
                        output.close();
                        input.close();
                    } catch (Exception e) {
                         e.printStackTrace();
                         Log.i("ERROR ON DOWNLOADING FILES", "ERROR IS" +e);
                    }
            }
        };
        dx.start();      
    }
  	    
    void downloadFile(){
    	
    	try {
    		URL url = new URL(dwnload_file_path);
    		HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
    		urlConnection.setRequestMethod("GET");
    		urlConnection.setDoOutput(true);

    		//connect
    		urlConnection.connect();

    		//set the path where we want to save the file    		
    		File SDCardRoot = Environment.getExternalStorageDirectory(); 
    		//create a new file, to save the downloaded file 
//    		File file = new File(SDCardRoot.getAbsolutePath() + "/mnt/sdcard/myclock/databases");
    		File file = new File(SDCardRoot.getAbsolutePath(), "ReviewerDAA.pdf");
 
    		FileOutputStream fileOutput = new FileOutputStream(file);

    		//Stream used for reading the data from the internet
    		InputStream inputStream = urlConnection.getInputStream();
    		System.out.println("--------- downloadFile()");
    		System.out.println(inputStream.equals(null));

    		//this is the total size of the file which we are downloading
    		totalSize = urlConnection.getContentLength();
    		System.out.println("totalSize : " + totalSize);

    		runOnUiThread(new Runnable() {
			    public void run() {
			    	pb.setMax(totalSize);
			    }			    
			});
    		
    		//create a buffer...
    		byte[] buffer = new byte[1024];
    		int bufferLength = 0;

    		while ( (bufferLength = inputStream.read(buffer)) > 0 ) {
    			fileOutput.write(buffer, 0, bufferLength);
    			downloadedSize += bufferLength;
    			// update the progressbar //
    			runOnUiThread(new Runnable() {
    			    public void run() {
    			    	pb.setProgress(downloadedSize);
    			    	float per = ((float)downloadedSize/totalSize) * 100;
    			    	cur_val.setText("Downloaded " + downloadedSize + "KB / " + totalSize + "KB (" + (int)per + "%)" );
    			    }
    			});
    		}
    		//close the output stream when complete //
    		fileOutput.close();
    		runOnUiThread(new Runnable() {
			    public void run() {
			    	// pb.dismiss(); // if you want close it..
			    }
			});    		
    	
    	} catch (final MalformedURLException e) {
    		showError("Error : MalformedURLException " + e);  		
    		Log.e("IOException", e.toString());
    	} catch (final IOException e) {
    		showError("Error : IOException " + e);  
    		Log.e("IOException", e.toString());
    	}
    	catch (final Exception e) {
    		showError("Error : Please check your internet connection " + e);
    	}    	
    }
    
    void showError(final String err){
    	runOnUiThread(new Runnable() {
		    public void run() {
		    	Toast.makeText(DownloadFileDemo1.this, err, Toast.LENGTH_LONG).show();
		    }
		});
    }
    
    void showProgress(String file_path){
    	dialog = new Dialog(DownloadFileDemo1.this);
    	dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
    	dialog.setContentView(R.layout.myprogressdialog);
    	dialog.setTitle("Download Progress");

    	TextView text = (TextView) dialog.findViewById(R.id.tv1);
    	text.setText("Downloading file from ... " + file_path);
    	cur_val = (TextView) dialog.findViewById(R.id.cur_pg_tv);
    	cur_val.setText("Starting download...");
    	dialog.show();
    	
    	pb = (ProgressBar)dialog.findViewById(R.id.progress_bar);
    	pb.setProgress(0);
    	pb.setProgressDrawable(getResources().getDrawable(R.drawable.green_progress));  
    }
}